package com.easa.controller;

import com.alibaba.fastjson.JSONObject;
import com.easa.entity.Semester;
import com.easa.entity.Weektable;
import com.easa.service.WeektableService;
import com.easa.util.DateUitls;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/weektable")
public class WeektableController {

    @Autowired
    private WeektableService weektableService;

    /*获取学期*/
    @RequestMapping(value="getSemesters.do",method= RequestMethod.GET)
    @ResponseBody
    public Object getSemesters(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        List<Semester> semesters = weektableService.findSemester();

        JSONObject js = new JSONObject();
        js.put("semesters",semesters);
        return js;
    }

    /*获取某学期以及周次*/
    @RequestMapping(value="getWeektable.do",method= RequestMethod.POST)
    @ResponseBody
    public Object getWeektable(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        String semesterId = request.getParameter("semesterid");
        Semester semester = weektableService.getSemesterById(semesterId);
        List<Weektable> weektables = weektableService.findWeekBySemesterId(semesterId);

        JSONObject js = new JSONObject();
        js.put("semester",semester);
        js.put("weeks",weektables);
        return js;
    }

    /*生成周次表*/
    @RequestMapping(value="produceWeeks.do",method= RequestMethod.POST)
    @ResponseBody
    public Object produceWeeks(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        JSONObject js = new JSONObject();
        String semesterId = request.getParameter("semesterId");
        String startDate = request.getParameter("startDate");
        String weekNumStr = request.getParameter("weekNum");
        String semesterName = request.getParameter("semesterName");

        Semester semester = new Semester();
        //查找是否存在该编号
        Semester exitSemester = weektableService.getSemesterById(semesterId);
        List<Weektable> weektables = new ArrayList<>();
        String formatDate = "yyyy-MM-dd";
        SimpleDateFormat dateFormat = new SimpleDateFormat(formatDate);
        Date dateStartCalendar = null;
        if(exitSemester==null){
            int weekNum  = 0;
            try {
                weekNum = Integer.parseInt(weekNumStr);
                semester.setWeekQuantity(weekNum);
            }catch (Exception e){
                System.out.println(e);
                js.put("isSuccess",2); //2为周数输入不正确
                return js;
            }

            try {
                dateStartCalendar = dateFormat.parse(startDate);
                GregorianCalendar calendar = new GregorianCalendar();
                calendar.setTime(dateStartCalendar);
                Date dateStartBefore = calendar.getTime();
                for (int i = 0; i < weekNum; i++) {
                    Weektable weektable = new Weektable();
                    weektable.setWeekid(semesterId+"_"+(i+1));
                    weektable.setWeekNum(i+1);
                    weektable.setSemester(semesterId);
                    weektable.setWeekStartDate(dateFormat.format(dateStartBefore)+" "+DateUitls.formateDay(calendar.get(Calendar.DAY_OF_WEEK)));

                    int j = 0;
                    //前进一天
                    for (Date date = dateStartBefore; !(j == 7); ) {
                        calendar.setTime(date);
                        calendar.add(Calendar.DATE, 1);
                        date = calendar.getTime();
                        j++;
                        dateStartBefore = date;
                        if (j==6)
                            weektable.setWeekEndDate(dateFormat.format(dateStartBefore)+" "+DateUitls.formateDay(calendar.get(Calendar.DAY_OF_WEEK)));
                    }
                    weektables.add(weektable);
                }
            }catch (ParseException e){
                e.printStackTrace();
            }
            semester.setSemesterStartDate(weektables.get(0).getWeekStartDate());
            semester.setSemesterEndDate(weektables.get(weekNum-1).getWeekEndDate());
        }else{
            js.put("isSuccess",1); //1表示该学期编号已存在
            return js;
        }

        semester.setSemesterId(semesterId);
        semester.setSemesterName(semesterName);
        js.put("semester",semester);
        js.put("weeks",weektables);
        js.put("isSuccess",0);
        return js;
    }

    /*保存周次表*/
    @RequestMapping(value="setWeeks.do",method= RequestMethod.POST)
    @ResponseBody
    public Object setWeeks(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        JSONObject js = new JSONObject();
        String semesterId = request.getParameter("semesterId");
        String startDate = request.getParameter("startDate");
        String weekNumStr = request.getParameter("weekNum");
        String semesterName = request.getParameter("semesterName");

        Semester semester = new Semester();
        //查找是否存在该编号
        Semester exitSemester = weektableService.getSemesterById(semesterId);
        List<Weektable> weektables = new ArrayList<>();
        String formatDate = "yyyy-MM-dd";
        SimpleDateFormat dateFormat = new SimpleDateFormat(formatDate);
        Date dateStartCalendar = null;
        int weekNum  = 0;
        if(exitSemester==null){
            try {
                weekNum = Integer.parseInt(weekNumStr);
                semester.setWeekQuantity(weekNum);
            }catch (Exception e){
                System.out.println(e);
                js.put("isSuccess",2); //2为周数输入不正确
                return js;
            }

            try {
                dateStartCalendar = dateFormat.parse(startDate);
                GregorianCalendar calendar = new GregorianCalendar();
                calendar.setTime(dateStartCalendar);
                Date dateStartBefore = calendar.getTime();
                for (int i = 0; i < weekNum; i++) {
                    Weektable weektable = new Weektable();
                    weektable.setWeekid(semesterId+"_"+(i+1));
                    weektable.setWeekNum(i+1);
                    weektable.setSemester(semesterId);
                    weektable.setWeekStartDate(dateFormat.format(dateStartBefore));

                    int j = 0;
                    //前进一天
                    for (Date date = dateStartBefore; !(j == 7); ) {
                        calendar.setTime(date);
                        calendar.add(Calendar.DATE, 1);
                        date = calendar.getTime();
                        j++;
                        dateStartBefore = date;
                        if (j==6)
                            weektable.setWeekEndDate(dateFormat.format(dateStartBefore));
                    }
                    weektables.add(weektable);
                }
            }catch (ParseException e){
                e.printStackTrace();
            }
            semester.setSemesterEndDate(weektables.get(weekNum-1).getWeekEndDate());
        }else{
            js.put("isSuccess",1); //1表示该学期编号已存在
            return js;
        }

        semester.setSemesterId(semesterId);
        semester.setSemesterName(semesterName);
        semester.setSemesterStartDate(startDate);

        int isSuccess = weektableService.setSemeter(semester);
        if (isSuccess==1){
            js.put("isSuccess",3); //学期保存错误
            return js;
        }

        //遍历weeks,存进数据库
        for (int i = 0; i < weekNum; i++){
            isSuccess = weektableService.setWeek(weektables.get(i));
            if(isSuccess==1){
                //删除周次 该学期
                weektableService.deleteWeeksBySid(semesterId);
                weektableService.deleteSemester(semesterId);
                js.put("isSuccess",4);//周次保存错误
                return js;

            }
        }

        js.put("isSuccess",0);
        return js;
    }

    /*删除学期周次*/
    @RequestMapping(value="deleteSemeterAndWeeks.do",method= RequestMethod.POST)
    @ResponseBody
    public Object deleteSemeterAndWeeks(HttpServletRequest request) throws ParseException, UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        String sid = request.getParameter("sid");
        //删除周次 该学期
        weektableService.deleteWeeksBySid(sid);
        weektableService.deleteSemester(sid);
        JSONObject js = new JSONObject();
        js.put("isSuccess",0);
        return js;
    }
}
